package com.ljb.calendar_demo;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.provider.CalendarContract;
import android.text.TextUtils;

import java.util.Calendar;
import java.util.TimeZone;

/**
 * 日历事件管理工具类
 * Created by lijianbin on 2017/4/1.
 */

public class CalendarKit {

    private static final String CALANDER_URL = "content://com.android.calendar/calendars";
    private static final String CALANDER_EVENT_URL = "content://com.android.calendar/events";
    private static final String CALANDER_REMIDER_URL = "content://com.android.calendar/reminders";
    private static final long ONE_HOUR = 1000 * 60 * 60;
    private static final String CALENDARS_NAME = "test";
    private static final String CALENDARS_ACCOUNT_NAME = "test@gmail.com";
    private static final String CALENDARS_ACCOUNT_TYPE = "com.android.exchange";
    private static final String CALENDARS_DISPLAY_NAME = "测试账户";
    private static CalendarKit kit;

    public static CalendarKit init() {
        if (kit == null)
            kit = new CalendarKit();
        return kit;
    }

    /**
     * 检查是否存在日历账户
     *
     * @param c 上下文
     * @return 存在返回账户id, 否则返回-1
     */
    private int checkCalendarAccount(Context c) {
        L.d("检查是否存在日历账户......");
        Cursor userCursor = c.getContentResolver().query(Uri.parse(CALANDER_URL), null, null, null, null);
        try {
            if (userCursor == null) {//查询结果为空
                L.d("查询结果为空");
                return -1;
            }

            int count = userCursor.getCount();//查询结果不为空
            if (count > 0) {//存在现有账户,获取第一个账户id返回
                userCursor.moveToFirst();
                int accountId = userCursor.getInt(userCursor.getColumnIndex(CalendarContract.Calendars._ID));
                L.d("存在现有账户,获取第一个账户id:" + accountId);
                return accountId;
            } else {
                L.d("查询结果不为空,但没有账户信息");
                return -1;
            }
        } finally {//关闭游标
            if (userCursor != null) {
                userCursor.close();
            }
        }
    }

    /**
     * 添加日历账户
     *
     * @param c 上下文
     * @return 添加成功返回账户id, 否则返回-1
     */
    private long addCalendarAccount(Context c) {
        L.d("开始添加日历账户.......");
        TimeZone timeZone = TimeZone.getDefault();

        ContentValues values = new ContentValues();
        values.put(CalendarContract.Calendars.NAME, CALENDARS_NAME);
        values.put(CalendarContract.Calendars.ACCOUNT_NAME, CALENDARS_ACCOUNT_NAME);
        values.put(CalendarContract.Calendars.ACCOUNT_TYPE, CALENDARS_ACCOUNT_TYPE);
        values.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, CALENDARS_DISPLAY_NAME);
        values.put(CalendarContract.Calendars.VISIBLE, 1);
        values.put(CalendarContract.Calendars.CALENDAR_COLOR, Color.BLUE);
        values.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);
        values.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
        values.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, timeZone.getID());
        values.put(CalendarContract.Calendars.OWNER_ACCOUNT, CALENDARS_ACCOUNT_NAME);
        values.put(CalendarContract.Calendars.CAN_ORGANIZER_RESPOND, 0);

        Uri calendarUri = Uri.parse(CALANDER_URL);
        calendarUri = calendarUri.buildUpon()
                .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, CALENDARS_ACCOUNT_NAME)
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, CALENDARS_ACCOUNT_TYPE)
                .build();

        Uri result = c.getContentResolver().insert(calendarUri, values);
        long id;
        if (result == null) {
            id = -1;
            L.d("添加账户失败");
        } else {
            id = ContentUris.parseId(result);
            L.d("添加账户成功");
        }
        return id;
    }

    /**
     * 获取日历账户
     *
     * @param c 上下文
     * @return 账户存在获取账户第, 不存在返回-1
     */
    private int checkAndAddCalendarAccount(Context c) {
        L.d("开始获取日历账户......");
        int oldId = checkCalendarAccount(c);
        if (oldId >= 0)//账户存在
            return oldId;

        long addId = addCalendarAccount(c);//账户不存在,添加一个账户
        if (addId >= 0)
            return checkCalendarAccount(c);

        return -1;
    }

    /**
     * 添加日历事件
     *
     * @param c           上下文
     * @param title       标题
     * @param description 事件描述
     * @param beginTime   开始时间戳
     * @return -1表示失败,1表示成功
     */
    public int addCalendarEvent(Context c, String title, String description, long beginTime) {
        L.d("添加日历事件......");
        //获取日历账户id
        int calId = checkAndAddCalendarAccount(c);
        if (calId < 0) { //获取账户id失败,添加日历事件失败
            L.d("获取账户id失败,添加日历事件失败");
            return -1;
        }

        ContentValues event = new ContentValues();
        event.put("title", title);
        event.put("description", description);
        event.put("calendar_id", calId);

        Calendar mCalendar = Calendar.getInstance();
        mCalendar.setTimeInMillis(beginTime);//设置开始时间
        long start = mCalendar.getTime().getTime();
        mCalendar.setTimeInMillis(start + ONE_HOUR);//设置终止时间
        long end = mCalendar.getTime().getTime();

        event.put(CalendarContract.Events.DTSTART, start);
        event.put(CalendarContract.Events.DTEND, end);
        event.put(CalendarContract.Events.HAS_ALARM, 1);//设置有闹钟提醒
        event.put(CalendarContract.Events.EVENT_TIMEZONE, "Asia/Beijing");  //这个是时区，必须有，
        //添加事件
        Uri newEvent = c.getContentResolver().insert(Uri.parse(CALANDER_EVENT_URL), event);
        if (newEvent == null) {// 添加日历事件失败直接返回
            L.d("获取账户id成功,添加日历事件失败");
            return -1;
        }

        //事件提醒的设定
        ContentValues values = new ContentValues();
        values.put(CalendarContract.Reminders.EVENT_ID, ContentUris.parseId(newEvent));
        // 提前10分钟有提醒
        values.put(CalendarContract.Reminders.MINUTES, 0);
        values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);
        Uri uri = c.getContentResolver().insert(Uri.parse(CALANDER_REMIDER_URL), values);
        if (uri == null) {
            // 添加闹钟提醒失败直接返回
            L.d("添加闹钟提醒失败");
            return -1;
        }
        L.d("添加闹钟提醒成功");
        return 1;//设置成功
    }

    /**
     * 根据设置的title来删除日历事件
     *
     * @param c     上下文
     * @param title 标题
     * @return -1表示删除失败,0表示没有查到该事件,1表示删除成功
     */
    public int deleteCalendarEvent(Context c, String title) {
        L.d("删除日历事件......");
        Cursor eventCursor = c.getContentResolver().query(Uri.parse(CALANDER_EVENT_URL), null, null, null, null);
        try {
            if (eventCursor == null) {//查询返回空值
                L.d("没有找到该事件");
                return 0;//没有找到该事件
            }

            if (eventCursor.getCount() > 0) {
                //遍历所有事件，找到title跟需要查询的title一样的项
                for (eventCursor.moveToFirst(); !eventCursor.isAfterLast(); eventCursor.moveToNext()) {
                    String eventTitle = eventCursor.getString(eventCursor.getColumnIndex("title"));
                    if (!TextUtils.isEmpty(title) && title.equals(eventTitle)) {
                        int id = eventCursor.getInt(eventCursor.getColumnIndex(CalendarContract.Calendars._ID));//取得id
                        Uri deleteUri = ContentUris.withAppendedId(Uri.parse(CALANDER_EVENT_URL), id);
                        int rows = c.getContentResolver().delete(deleteUri, null, null);
                        if (rows == -1) {
                            //事件删除失败
                            L.d("事件删除失败");
                            return -1;
                        }
                    }
                }
            }

            L.d("事件删除成功");
            return 1;//删除成功

        } finally {
            if (eventCursor != null) {
                eventCursor.close();
            }
        }
    }
}






















